"""
岗位管理序列化器
"""
from rest_framework import serializers
from django.contrib.auth import get_user_model
from students.models import Student
from .models import Company, Job, JobApplication

User = get_user_model()


class CompanySerializer(serializers.ModelSerializer):
    """公司序列化器"""
    
    class Meta:
        model = Company
        fields = [
            'id', 'name', 'code', 'company_type', 'company_size',
            'industry', 'website', 'description', 'address',
            'contact_person', 'contact_phone', 'contact_email',
            'logo', 'founded_year', 'employee_count',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']


class CompanyListSerializer(serializers.ModelSerializer):
    """公司列表序列化器"""
    
    class Meta:
        model = Company
        fields = [
            'id', 'name', 'company_type', 'company_size',
            'industry', 'address', 'created_at'
        ]
        read_only_fields = ['id', 'created_at']


class JobSerializer(serializers.ModelSerializer):
    """岗位序列化器"""
    
    company_info = CompanyListSerializer(source='company', read_only=True)
    published_by_name = serializers.CharField(source='published_by.username', read_only=True)
    salary_range = serializers.CharField(read_only=True)
    
    class Meta:
        model = Job
        fields = [
            'id', 'company', 'company_info', 'title', 'job_type', 'work_mode',
            'department', 'salary_min', 'salary_max', 'salary_negotiable',
            'work_location', 'remote_allowed', 'description', 'requirements',
            'responsibilities', 'benefits', 'required_skills', 'preferred_skills',
            'education_requirement', 'experience_requirement', 'positions_available',
            'application_deadline', 'contact_email', 'contact_phone',
            'is_long_term', 'valid_from', 'valid_until', 'status', 'is_featured',
            'published_by', 'published_by_name', 'published_at', 'salary_range',
            'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'company_info', 'published_by_name', 'salary_range',
            'published_by', 'published_at', 'created_at', 'updated_at'
        ]
    
    def validate(self, data):
        """验证数据"""
        # 如果不是长期有效，必须设置有效期
        if not data.get('is_long_term', False):
            if not data.get('valid_from') or not data.get('valid_until'):
                raise serializers.ValidationError("非长期有效岗位必须设置有效期")
        
        # 薪资验证
        if not data.get('salary_negotiable', False):
            if data.get('salary_min') and data.get('salary_max'):
                if data['salary_min'] > data['salary_max']:
                    raise serializers.ValidationError("最低薪资不能大于最高薪资")
        
        return data


class JobListSerializer(serializers.ModelSerializer):
    """岗位列表序列化器"""
    
    company_name = serializers.CharField(source='company.name', read_only=True)
    company_address = serializers.CharField(source='company.address', read_only=True)
    published_by_name = serializers.CharField(source='published_by.username', read_only=True)
    salary_range = serializers.CharField(read_only=True)
    
    class Meta:
        model = Job
        fields = [
            'id', 'company', 'company_name', 'company_address', 'title',
            'job_type', 'work_mode', 'work_location', 'salary_range',
            'education_requirement', 'positions_available', 'contact_email',
            'contact_phone', 'is_long_term', 'valid_until', 'status',
            'is_featured', 'published_by_name', 'published_at', 'created_at'
        ]
        read_only_fields = [
            'id', 'company_name', 'company_address', 'published_by_name',
            'salary_range', 'created_at'
        ]


class JobCreateSerializer(serializers.ModelSerializer):
    """岗位创建序列化器"""
    
    class Meta:
        model = Job
        fields = [
            'company', 'title', 'job_type', 'work_mode', 'department',
            'salary_min', 'salary_max', 'salary_negotiable', 'work_location',
            'remote_allowed', 'description', 'requirements', 'responsibilities',
            'benefits', 'required_skills', 'preferred_skills',
            'education_requirement', 'experience_requirement', 'positions_available',
            'application_deadline', 'contact_email', 'contact_phone',
            'is_long_term', 'valid_from', 'valid_until', 'is_featured'
        ]
    
    def validate(self, data):
        """验证数据"""
        # 如果不是长期有效，必须设置有效期
        if not data.get('is_long_term', False):
            if not data.get('valid_from') or not data.get('valid_until'):
                raise serializers.ValidationError("非长期有效岗位必须设置有效期")
        
        # 薪资验证
        if not data.get('salary_negotiable', False):
            if data.get('salary_min') and data.get('salary_max'):
                if data['salary_min'] > data['salary_max']:
                    raise serializers.ValidationError("最低薪资不能大于最高薪资")
        
        return data


class JobApplicationSerializer(serializers.ModelSerializer):
    """岗位申请序列化器"""
    
    job_info = JobListSerializer(source='job', read_only=True)
    student_info = serializers.SerializerMethodField()
    reviewed_by_name = serializers.CharField(source='reviewed_by.username', read_only=True)
    
    class Meta:
        model = JobApplication
        fields = [
            'id', 'job', 'job_info', 'student', 'student_info',
            'cover_letter', 'resume_file', 'status', 'reviewed_by',
            'reviewed_by_name', 'review_comments', 'reviewed_at',
            'applied_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'job_info', 'student_info', 'reviewed_by_name',
            'reviewed_by', 'reviewed_at', 'applied_at', 'updated_at'
        ]
    
    def get_student_info(self, obj):
        """获取学生信息"""
        if obj.student:
            return {
                'id': obj.student.id,
                'student_id': obj.student.student_id,
                'name': obj.student.name,
                'email': obj.student.email,
                'phone': obj.student.phone,
                'grade': obj.student.grade.name if obj.student.grade else None
            }
        return None


class JobApplicationListSerializer(serializers.ModelSerializer):
    """岗位申请列表序列化器"""
    
    job_title = serializers.CharField(source='job.title', read_only=True)
    company_name = serializers.CharField(source='job.company.name', read_only=True)
    student_name = serializers.CharField(source='student.name', read_only=True)
    student_id = serializers.CharField(source='student.student_id', read_only=True)
    
    class Meta:
        model = JobApplication
        fields = [
            'id', 'job', 'job_title', 'company_name', 'student',
            'student_name', 'student_id', 'status', 'applied_at'
        ]
        read_only_fields = [
            'id', 'job_title', 'company_name', 'student_name',
            'student_id', 'applied_at'
        ]


class MyJobApplicationSerializer(serializers.ModelSerializer):
    """我的岗位申请序列化器（学生用）"""
    
    job_title = serializers.CharField(source='job.title', read_only=True)
    company_name = serializers.CharField(source='job.company.name', read_only=True)
    company_address = serializers.CharField(source='job.company.address', read_only=True)
    contact_email = serializers.CharField(source='job.contact_email', read_only=True)
    contact_phone = serializers.CharField(source='job.contact_phone', read_only=True)
    work_location = serializers.CharField(source='job.work_location', read_only=True)
    salary_range = serializers.CharField(source='job.salary_range', read_only=True)
    
    class Meta:
        model = JobApplication
        fields = [
            'id', 'job', 'job_title', 'company_name', 'company_address',
            'contact_email', 'contact_phone', 'work_location', 'salary_range',
            'status', 'cover_letter', 'resume_file', 'review_comments',
            'applied_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'job_title', 'company_name', 'company_address',
            'contact_email', 'contact_phone', 'work_location', 'salary_range',
            'applied_at', 'updated_at'
        ]
